<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>[3.11]-扩展类库：基于FastRoute的快速路由 | PhalApi(π框架) - PHP轻量级开源接口框架 - 助你创造价值！</title>
    <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
    <meta content="yes" name="apple-mobile-web-app-capable">
    <meta content="black" name="apple-mobile-web-app-status-bar-style">
    <meta content="telephone=no" name="format-detection">
    <meta content="email=no" name="format-detection">
    <meta name="Author" content="PhalApi,ecitlm,dogstar">
    <meta name="description" content="[3.11]-扩展类库：基于FastRoute的快速路由，PhalApi是一个PHP轻量级开源接口框架，致力于快速开发接口服务。支持HTTP/SOAP/RPC等协议，可用于搭建接口/微服务/RESTful接口/Web Services。我们不断更新，保持生气；为接口负责，为开源负责！并承诺永久免费！">
    <meta name="keywords" content="PhalApi,phalapi,phalapi接口开发,后台接口开发,后台接口开发框架,接口开发,接口框架,开源接口框架,PHP后台接口开发,PHP接口开发,PHP接口框架,PHP后台接口框架,phalapi官网,PHP接口框架,php接口开发框架,php接口开发,php web框架,π框架,π开发框架,π接口框架,π接口开发框架,api接口,php接口,,PHP接口框架,phalapi文档,phalapi wiki,PhalApi文档,phalapi在线文档,phalapi官方文档">

    <link rel="stylesheet" type="text/css" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" media="screen">
    <link rel="stylesheet" type="text/css" href="https://cdn.bootcss.com/font-awesome/4.7.0/css/font-awesome.css" media="screen">
    <link rel="stylesheet" href="../css/main.css" />
    <link rel="stylesheet" href="../css/loading_bar.css" />
    <link rel="icon" href="http://webtools.qiniudn.com/dog_catch.png" type="image/x-icon" />
    <script src="../js/pace.min.js"></script>
	
	<!-- 代码高亮 -->
	<link rel="stylesheet" href="../css/highlight.min.css">
	<script src="../js/highlight.min.js"></script>
	<script>hljs.initHighlightingOnLoad();</script>
    
</head>

<body>
    <!-- navbar start -->
    <div class="navbar navbar-default navbar-fixed-top" id="mainnav" role="navigation">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target=".navbar-collapse">
                    <span class="sr-only">Toggle navigation</span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                <a class="navbar-brand website_name" href="/"><!-- <span>PhalApi</span> --><strong>PhalApi</strong></a>
            </div>
            <div class="navbar-collapse collapse" aria-expanded="false" style="height: 1px;">
                <ul class="nav navbar-nav navbar-right" id="nav_bar">
                    <li><a href="/"><span class="glyphicon glyphicon-home"></span></a></li>
                    <li><a href="http://qa.phalapi.net/">社区</a></li>
                    <li><a href="/download.html">下载</a></li>
                    <li class="active"><a href="/wikis/">文档</a></li>
                    <li><a href="http://www.ituring.com.cn/book/2405">书籍</a></li>
                    <li><a href="http://demo.phalapi.net/">体验</a></li>
                    <li><a href="/about.html">关于</a></li>
                    <li><a href="/donate.html">贡献</a></li>
                    <li><a href="/wikis/en/">English</a></li>
                </ul>
            </div>
            <!--/.nav-collapse -->
        </div>
    </div>
    <!-- navbar end -->


    <div id="content">
        <div class="container">
            <div class="row row-md-flex row-md-flex-wrap">
                <h4><a href="#">上一章</a>   <a href="/wikis/">文档首页</a>   <a href="#">下一章</a></h4>
<hr />
<h2>3.11.1 扩展类库：基于FastRoute的快速路由</h2>
<p>此扩展基于 <a href="https://github.com/nikic/FastRoute">FastRoute</a> 实现，需要 <strong>PHP 5.4.0</strong> 及以上版本，可以通过配置实现自定义路由配置，从而轻松映射到PhalApi中的service接口服务。  </p>
<h2>3.11.2 安装和配置</h2>
<h3>(1)扩展包下载</h3>
<p>从  <a href="http://git.oschina.net/dogstar/PhalApi-Library">PhalApi-Library</a>  扩展库中下载获取 <strong>FastRoute</strong> 扩展包，如使用：</p>
<pre><code class="language-bash">$ git clone https://git.oschina.net/dogstar/PhalApi-Library.git</code></pre>
<p>然后把 <strong>FastRoute</strong> 目录复制到 <strong>./PhalApi/Library/</strong> 下，即：</p>
<pre><code class="language-bash">$ cp ./PhalApi-Library/FastRoute/ ./PhalApi/Library/ -R</code></pre>
<p>到此安装完毕！接下是插件的配置。</p>
<h3>(2)扩展包配置</h3>
<p>我们需要在 <strong>./Config/app.php</strong> 配置文件中追加以下配置：</p>
<pre><code class="language-php">    /**
     * 扩展类库 - 快速路由配置
     */
    'FastRoute' =&gt; array(
         /**
          * 格式：array($method, $routePattern, $handler)
          *
          * @param string/array $method 允许的HTTP请求方式，可以为：GET/POST/HEAD/DELETE 等
          * @param string $routePattern 路由的正则表达式
          * @param string $handler 对应PhalApi中接口服务名称，即：?service=$handler
          */
        'routes' =&gt; array(
            array('GET', '/user/get_base_info/{user_id:\d+}', 'User.GetBaseInfo'),
            array('GET', '/user/get_multi_base_info/{user_ids:[0-9,]+}', 'User.GetMultiBaseInfo'),
        ),
    ),
</code></pre>
<h3>(3)nginx的协助配置（省略index.php）</h3>
<p>如果是使用nginx的情况下，需要添加以下配置：</p>
<pre><code>    # 最终交由index.php文件处理
    location / {
        try_files $uri $uri/ $uri/index.php;
    }

    # 匹配未找到的文件路径
    if (!-e $request_filename) {
        rewrite ^/(.*)$ /index.php/$1 last;
    }</code></pre>
<p>然后重启nginx。  </p>
<h2>3.11.3 入门使用</h2>
<h3>(1)入口注册</h3>
<pre><code class="language-php">//$ vim ./Public/index.php

$loader-&gt;addDirs('Library');

// 其他代码....

//显式初始化，并调用分发
DI()-&gt;fastRoute = new FastRoute_Lite();
DI()-&gt;fastRoute-&gt;dispatch();

/** ---------------- 响应接口请求 ---------------- **/

$api = new PhalApi();
$rs = $api-&gt;response();
$rs-&gt;output();</code></pre>
<h2>3.11.3 调用效果及扩展</h2>
<h3>(1)通过新的路由正常访问</h3>
<p>在完成上面的配置后，我们就可以这样进行页面访问测试：</p>
<pre><code>  http://library.phalapi.com/user/get_base_info/1
  等效于：http://library.phalapi.com/?service=User.GetBaseInfo&amp;user_id=1

  http://library.phalapi.com/user/get_multi_base_info/1,2
  等效于：http://library.phalapi.com/?service=User.GetMultiBaseInfo&amp;user_ids=1,2</code></pre>
<h3>(2)非法访问</h3>
<p>当请求的HTTP方法与配置的不符合时，就会返回405错误，如我们配置了：</p>
<pre><code class="language-php">array('POST', '/user/{id:\d+}/{name}', 'handler2'),</code></pre>
<p>但是通过GET方式来访问，即：</p>
<pre><code>http://library.phalapi.com/user/123/name</code></pre>
<p>则会返回：</p>
<pre><code>{
    "ret": 405,
    "data": [],
    "msg": "快速路由的HTTP请求方法错误，应该为：POST"
}</code></pre>
<h3>(3)路由配置错误</h3>
<p>当在./Config/app.php的文件里配置错误的路由时，会直接抛出FastRoute\BadRouteException异常，以及时提示开发人员修正。</p>
<h3>(4)异常错误处理器</h3>
<p>我们也可以实现FastRoute_Handler接口来自定义我们自己的错误异常处理回调函数。如：</p>
<pre><code class="language-php">class FastRoute_Handler_App implements FastRoute_Handler {

    public function excute(PhalApi_Response $response) {
        // ... ...
    }
}</code></pre>
<p>然后，在分发时指定handler：</p>
<pre><code class="language-php">DI()-&gt;fastRoute-&gt;dispatch(new FastRoute_Handler_App());</code></pre>
<h3>3.11.4 更多路由配置说明</h3>
<p>请访问 <a href="https://github.com/nikic/FastRoute">FastRoute</a> ，查看其官方说明。</p>
<h4><a href="#">上一章</a>   <a href="/wikis/">文档首页</a>   <a href="#">下一章</a></h4><div style="float: left">
<h4>
<a href="http://qa.phalapi.net/">还有疑问？欢迎到社区提问！</a>
</h4>
</div>
            </div>
        </div>
    </div>

 <!-- 广告位 -->
<div class="grid-wrapper desktop-only">
	<p align="center">
		<a href="http://7xiz2f.com1.z0.glb.clouddn.com/%E6%88%91%E7%9A%84%E5%90%8D%E5%AD%97%E5%8F%AB%EF%BC%9A%CF%80%E6%A1%86%E6%9E%B6%20-%20PhalApi%202016%E5%B9%B4%E5%BA%A6%E5%BC%80%E6%BA%90%E6%80%BB%E7%BB%93%20-%20%E5%AE%98%E6%96%B9%E5%87%BA%E5%93%81.pdf" target="blank"><img width="950" height="100" src="http://7xiz2f.com1.z0.glb.clouddn.com/ad_20170104.png"></a>
		<a href="http://www.itran.cc/" target="blank"><img width="950" height="100" src="http://7xslqv.com1.z0.glb.clouddn.com/images/9/69/b88bc92455dc1239f9a5bf8d72929.png"></a>
		<a href="http://web-tools.phalapi.net/" target="blank"><img width="950" height="100" src="http://7xslqv.com1.z0.glb.clouddn.com/images/7/d0/88f523566c482296aecc43d185ca2.png"></a>
	</p>
</div>

        <!-- footer -->
        <div class="footer">
            <div class="link container ">
                <div class=" col-xs-7 col-sm-7 col-md-7 col-lg-7 ">
                    <h3>PhalApi (π框架)</h3>
                    <p>一个轻量级PHP开源接口框架，专注于接口服务开发，支持HTTP/SOAP/RPC协议，拥有自动生成的在线文档、多种开发语言的客户端SDK包以及可重用的扩展类库，可用于快速搭建微服务、RESTful接口或Web
                        Services。</p>
                    <!-- <p>:</p> -->
                    <span>友情链接:</span>
                    <a href="https://www.phalapi.net/" target="_blank"> PhalApi </a>
                    <a href="http://www.oschina.net/" target="_blank"> 开源中国 </a>
                    <a href="https://www.itran.cc/" target="_blank">艾翻译</a>
                    <a href="http://www.phalconphp.com/en/" target="_blank">Phalcon</a>
                    <a href="https://phpunit.de/manual/3.7/zh_cn/automating-tests.html" target="_blank">PHPUnit</a>
                    <a href="http://www.thoughtworks.com/cn/" target="_blank">ThoughtWorks</a>
                    <a href="mailto:chanzonghuang@gmail.com">友链交换</a>

                </div>
                <div class=" col-xs-5 col-sm-5 col-md-5 col-lg-5 contact_us ">
                    <h3>联系我们</h3>
                    <a href="https://github.com/phalapi/phalapi"><img src="../images/github.png" alt="github" /></a>
                    <a href="http://weibo.com/p/100808d236e99beb645bfb56ed1c37dde9b8bd?k=phalapi%E5%BC%80%E6%BA%90%E6%A1%86%E6%9E%B6&from=501&_from_=huati_topic"><img src="../images/weibo.png"  alt="weibo" /></a>
                    <a href="http://7xslqv.com1.z0.glb.clouddn.com/images/1/b0/894fde762850cb11250253f7d5ede.png"><img src="../images/zfb.png"  alt="zfb" /></a>
                    <a href="https://jq.qq.com/?_wv=1027&k=4A6reum"><img src="../images/qq.png"  alt="qq" /></a>
					<a href="http://git.oschina.net/dogstar/PhalApi"><img src="../images/git-oschina.png"  alt="git-oschina" /></a>
                </div>
                <div class="cls"></div>
                <div class="text-center copy_right"> ©2015-2017 PhalApi All Rights Reserved. <a href="http://www.miitbeian.gov.cn" target="_blank">粤ICP备15028808号</a>

				<script type="text/javascript">var cnzz_protocol = (("https:" == document.location.protocol) ? " https://" : " http://");document.write(unescape("%3Cspan id='cnzz_stat_icon_1255326144'%3E%3C/span%3E%3Cscript src='" + cnzz_protocol + "s4.cnzz.com/z_stat.php%3Fid%3D1255326144%26show%3Dpic' type='text/javascript'%3E%3C/script%3E"));</script>
                </div>
            </div>
        </div>
    </div>


    <a href="https://github.com/phalapi"><img id="gitHub_fllow" style="position: fixed; top: 0; right: 0; border: 0;z-index:9999" src="https://camo.githubusercontent.com/652c5b9acfaddf3a9c326fa6bde407b87f7be0f4/68747470733a2f2f73332e616d617a6f6e6177732e636f6d2f6769746875622f726962626f6e732f666f726b6d655f72696768745f6f72616e67655f6666373630302e706e67" alt="Fork me on GitHub" data-canonical-src="https://s3.amazonaws.com/github/ribbons/forkme_right_orange_ff7600.png"></a>


    <script src="../js/jquery-1.11.1.min.js"></script>
    <script src="../js/bootstrap.min.js"></script>
</body>

</html>